<template>
  <div class="order-content">
    <!-- <van-row class="login-header" v-show="isIconShow">
      <van-col span="7" class="icon-content">
        <van-icon name="arrow-left" @click="onReturn" />
      </van-col>
      <van-col span="24">{{title}}</van-col>
    </van-row>-->
    <van-row class="login-header">
      <van-col span="24">{{title}}</van-col>
    </van-row>
    <van-collapse v-model="activeNames" class="orderTable-content">
      <van-collapse-item title="订单头信息" name="0">
        <!-- @submit="onSubmit()" -->
        <van-form ref="orderForm">
          <van-field
            readonly
            clickable
            name="voucherdate"
            :value="formData.voucherdate"
            label="单据日期"
            placeholder="点击选择日期"
            :rules="[{ required: true, message: '请选择单据日期' }]"
            @click="showCalendar = true"
          />
          <van-field v-model="formData.code" name="code" label="单据编号" readonly />
          <van-field v-model="formData.busitypeName" name="busitypeName" label="业务类型" readonly />
          <van-popup v-model="typeShowPicker" position="bottom">
            <van-picker
              show-toolbar
              :columns="typeColumns"
              @confirm="onConfirmType"
              @cancel="typeShowPicker = false"
            />
          </van-popup>
          <van-field v-model="formData.reciveType" name="reciveType" label="收款方式" readonly />
          <van-field
            readonly
            clickable
            name="iddepartment"
            label="部门"
            placeholder="请选择部门"
            :value="iddepartment"
            @click="orgShowPicker = true"
          />
          <!-- <van-popup v-model="orgShowPicker" round position="bottom" :style="{ height: '30%' }">
            <van-cell-group>
              <van-cell
                v-for="(item, index) in orgColumns"
                :key="index"
                :title="item.name"
                @click="onConfirmOrg(item)"
              />
            </van-cell-group>
          </van-popup>-->
          <van-field
            readonly
            clickable
            name="idclerk"
            label="业务员"
            placeholder="请先选择部门"
            :value="idclerk"
            @click="perShowPicker = true"
          />
          <!-- <van-popup v-model="perShowPicker" round position="bottom" :style="{ height: '30%' }">
            <van-cell-group>
              <van-cell
                v-for="(item, index) in perColumns"
                :key="index"
                :title="item.name"
                @click="onConfirmPer(item)"
              />
            </van-cell-group>
          </van-popup>-->
          <!-- 是否账期 -->
          <van-field name="pubuserdefnvc1" label="是否账期" @click="onSelectZhangqi">
            <template #input>
              <van-radio-group
                v-model="formData.pubuserdefnvc1"
                direction="horizontal"
                :disabled="status"
              >
                <van-radio name="是">是</van-radio>
                <van-radio name="否">否</van-radio>
              </van-radio-group>
            </template>
          </van-field>
          <!-- 賬期到期時間 -->
          <van-field
            v-show="formData.pubuserdefnvc1==='是'"
            readonly
            clickable
            name="pubuserdefnvc3"
            :value="formData.pubuserdefnvc3"
            label="账期到期时间"
            placeholder="点击选择账期到期时间"
            :rules="[{ required: true, message: '选择账期到期时间' }]"
            @click="showCalendar2 = true"
          />
          <van-calendar v-if="!status" v-model="showCalendar2" @confirm="onConfirm2" />
          <!-- 包邮 -->
          <van-field name="pubuserdefnvc8" label="是否包邮" @click="onSelectBaoyou">
            <template #input>
              <van-radio-group
                :disabled="status"
                v-model="formData.pubuserdefnvc8"
                direction="horizontal"
              >
                <van-radio name="包邮">包邮</van-radio>
                <van-radio name="到付">到付</van-radio>
                <van-radio name="自提">自提</van-radio>
                <!-- <van-radio name="是">是</van-radio>
                <van-radio name="否">否</van-radio> -->
              </van-radio-group>
            </template>
          </van-field>
          <van-field
            v-show="formData.pubuserdefnvc8==='否'"
            v-model="formData.pubuserdefdecm2"
            :readonly="status"
            name="pubuserdefdecm2"
            type="number"
            label="运费"
            placeholder="请输入运费"
          />
          <!-- 客户 -->
          <!-- <van-field v-show="status" readonly v-model="formData.partnerName" label="客户" /> -->
          <!-- name="partnerName -->
          <van-cell is-link @click="showPopup" :value="formData.partnerName">
            <template #title>
              <span class="custom-title">客户</span>
            </template>
          </van-cell>
          <van-popup
            class="popup-class"
            v-model="show"
            position="bottom"
            :style="{ height: '100%' }"
          >
            <!-- round -->
            <van-sticky :offset-top="0">
              <van-row>
                <van-col span="20">
                  <van-search
                    class="search-content"
                    v-model="condition"
                    shape="round"
                    placeholder="请输入客户名称"
                    @input="onFindClient()"
                  />
                </van-col>
                <van-col span="4">
                  <van-button plain round hairline type="default" @click="onCancelDig()">取消</van-button>
                </van-col>
              </van-row>
            </van-sticky>

            <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
              <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
                <van-cell-group>
                  <van-cell
                    v-for="(item, index) in cusColumns"
                    :key="index"
                    :title="item.name"
                    @click="onConfirmCus(item)"
                  />
                </van-cell-group>
              </van-list>
            </van-pull-refresh>
          </van-popup>
          <!-- <van-field
            v-model="formData.idsettlecustomer"
            name="code"
            label="客户应收账"
            placeholder="请输入客户应收账"
          />-->
          <!-- 结算客户 -->
          <!-- <van-field v-show="status" v-model="formData.settlecustomerName" readonly label="结算客户" /> -->
          <van-cell is-link @click="showPopup2" :value="formData.settlecustomerName">
            <template #title>
              <span class="custom-title">结算客户</span>
            </template>
          </van-cell>
          <van-popup
            class="popup-class"
            v-model="show2"
            position="bottom"
            :style="{ height: '100%' }"
          >
            <!-- round -->
            <van-sticky :offset-top="0">
              <van-row>
                <van-col span="20">
                  <van-search
                    class="search-content"
                    v-model="condition"
                    shape="round"
                    placeholder="请输入客户名称"
                    @input="onFindClient()"
                  />
                </van-col>
                <van-col span="4">
                  <van-button plain round type="default" hairline @click="onCancelDig()">取消</van-button>
                </van-col>
              </van-row>
            </van-sticky>
            <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
              <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
                <van-cell-group>
                  <van-cell
                    v-for="(item, index) in cusColumns"
                    :key="index"
                    :title="item.name"
                    @click="onConfirmSetCus(item)"
                  />
                </van-cell-group>
              </van-list>
            </van-pull-refresh>
          </van-popup>

          <van-field
            name="address"
            v-model="formData.address"
            center
            clearable
            label="收货地址"
            placeholder="请选择收货地址"
            :readonly="status"
          >
            <template #button>
              <van-button
                size="small"
                type="info"
                :disabled="status"
                @click="addressShowPicker = true"
              >选择</van-button>
            </template>
          </van-field>
          <van-popup v-model="addressShowPicker" round position="bottom" :style="{ height: '30%' }">
            <van-cell-group>
              <van-cell
                v-for="(item, index) in addColumns"
                :key="index"
                :title="item.address"
                @click="onConfirmAddress(item)"
              />
            </van-cell-group>
          </van-popup>
          <van-field
            clickable
            name="address"
            label="联系人"
            placeholder="请输入联系人"
            v-model="formData.linkMan"
            :readonly="status"
          />
          <van-field
            clickable
            type="tel"
            name="address"
            label="联系电话"
            placeholder="请输入联系电话"
            v-model="formData.contactPhone"
            :readonly="status"
          />
          <van-field
            clickable
            name="waybillNumber"
            label="快递单号"
            readonly
            v-show="title==='查看订单'"
            v-model="formData.waybillNumber"
          />
          <van-field v-model="formData.memo" name="memo" label="仓库备注" :readonly="status" />
          <van-field v-model="formData.pubuserdefnvc4" name="pubuserdefnvc4" label="财务备注" :readonly="status" />

          <van-cell>
            <template #title>
              <span class="custom-title">水单上传</span>
            </template>
          </van-cell>
          <van-uploader
            style="margin-top:5px"
            v-model="fileList"
            multiple
            :after-read="afterRead"
            :max-size="5*1024*1024"
            @oversize="onOversize"
            :disabled="status"
          />
          <!-- <van-field v-model="formData.code" name="code" label="业务员应收账" placeholder="请输入业务员应收账" /> -->
        </van-form>
      </van-collapse-item>
      <!-- 存货 -->
      <van-cell is-link @click="onSelectGoods" v-show="!status" :value="idinventory">
        <template #title>
          <span class="custom-title">选择存货</span>
        </template>
      </van-cell>
      <!-- 订单明细列表 -->
      <van-swipe-cell v-for="(item, index) in tempArr" :key="index">
        <!-- v-for="(item, index) in goodColumns" :key="index" -->
        <van-card currency style="margin-bottom:5px">
          <template #title>
            <div style="text-align:left">{{item.name}}</div>
          </template>
          <template #desc>
            <div style="text-align:left;color:#cccccc">{{item.code}}</div>
            <div style="text-align:left;margin-bottom:5px;">
              <van-tag plain type="primary">单位：{{item.unitName}}</van-tag>
              <van-tag plain round type="success">{{item.inventoryclassName}}</van-tag>
              <van-tag v-if="item.gift===1" plain round type="warning">赠品</van-tag>
            </div>
            <van-row>
              <van-col span="24" v-if="item.gift===0" style="margin-bottom:5px">
                <van-col span="12">
                  <van-field
                    v-model="item.price"
                    type="number"
                    label="单价"
                    @input="onJudgePrice(item)"
                    placeholder="输入单价"
                    :disabled="status"
                    style="background-color:#FAFAFA"
                  />
                </van-col>
                <!-- <van-col span="12">
                                <van-field v-model="item.invSCost" type="number" label="最低售价" readonly style="background-color:#FAFAFA" />
                </van-col>-->
              </van-col>
              <van-col span="24">
                <van-col span="4">数量：</van-col>
                <van-col span="5">
                  <van-stepper
                    v-model="item.quantity"
                    theme="round"
                    button-size="18"
                    :disabled="status"
                    @change="onCountNum(item)"
                  />
                </van-col>
                <van-col span="8">单位(箱):{{item.quantity2}}</van-col>
                <!-- ({{item.unitName2}}) -->
                <van-col span="7" style="color:#EE0A24">￥{{item.total}}</van-col>
              </van-col>
            </van-row>
            <!-- <van-col span="8">
                <div style="color:#EE0A24;margin-top:13px">￥{{item.total}}</div>
            </van-col>-->
          </template>
        </van-card>
        <template #right>
          <van-button square type="danger" text="删除" @click="onDelTeamArr(index)" />
        </template>
      </van-swipe-cell>
      <div v-if="tempArr.length!=0">
        <span style="float:right;margin-right:20px;margin-bottom:10px;color:#EE0A24">合计￥：{{total}}</span>
      </div>
      <div style="margin: 16px 16px 70px 16px;">
        <van-button
          round
          block
          :loading="submitLoading"
          type="info"
          :disabled="status"
          @click="onSubmit"
        >提交</van-button>
      </div>
    </van-collapse>
  </div>
</template>

<script>
import {
  queryCode,
  queryPerson,
  queryClient,
  queryOrgs,
  queryUnits,
  submitOrder,
  queryGoods,
  queryAddress,
} from "@/api/order/order";
import { delPic } from "@/api/public/public";
import eventBus from "@/api/public/eventBus";
// 提示框
import { Dialog } from "vant";
import { Toast } from "vant";
import { queryOrderDetial, updateOrder } from "@/api/search/search";
// 引入vuex
import { mapMutations } from "vuex";

export default {
  data() {
    return {
      // 防抖计时器
      timeout: "",
      // 订单只读
      status: false,
      // 按钮加载
      submitLoading: false,
      // 合计订单价格
      total: 0,
      // 下拉翻页
      list: [],
      page: 1,
      limit: 10,
      count: "", //总数
      loading: false,
      finished: false,
      refreshing: false,
      // 单价验证
      errorMessage: "",
      // 数量2
      quantity2: "",
      // 文件上传列表
      fileList: [],
      // 标题
      title: "下单",
      // 搜索
      show: false,
      show2: false,
      show3: false,
      condition: "",
      condition2: "",
      condition3: "",
      // 业务类型
      // idbusinesstype: "65"
      typeColumns: [
        {
          text: "普通销售",
          busitypeName: "普通销售",
        },
      ],
      typeShowPicker: false,
      // 存货
      idinventory: "", //名称
      idinventory2: "", //index索引
      goodColumns: [],
      goodShowPicker: false,
      // 计量单位
      idunit: "",
      idunit2: "",
      // 部门
      iddepartment: "",
      orgColumns: [],
      orgShowPicker: false,
      // 地址
      addColumns: [],
      addressShowPicker: false,
      // 客户
      partnerName: "",
      cusColumns: [],
      cusShowPicker: false,
      // 结算客户
      settlecustomerName: "",
      setCusColumns: [],
      setCusShowPicker: false,
      // 业务员
      idclerk: "",
      perColumns: [],
      perShowPicker: false,
      code: "",
      id: "",
      // 表单数据
      formData: {
        voucherdate: "",
        linkMan: "",
        waybillNumber: "",
        contactPhone: "",
        memo: "",
        pubuserdefnvc4: "",
        address: "",
        code: "",
        busitypeName: "普通销售",
        idcustomer: "",
        partnerName: "",
        idclerk: "",
        iddepartment: "",
        reciveType: "其他",
        idsettlecustomer: "",
        settlecustomerName: "",
        // 是否账期单选
        pubuserdefnvc1: "否",
        // 是否包邮
        pubuserdefnvc8: "包邮",
        // 运费
        pubuserdefdecm2: 0,
        // 账期到期时间
        pubuserdefnvc3: "",
        // 文件数组
        fileList: [],
      },
      // 表单数据
      formData2: {
        name: "",
        price: "",
        invSCost: "",
        unitName2: "",
        unitName: "",
        idunit: "",
        idunit2: "",
        quantity: "",
        quantity2: "",
      },
      // 数量换算率
      unitExchangeRate: 1,
      // 折叠面板
      activeNames: ["0", "1"],
      items: 1,
      //   日期
      value: "",
      pubuserdefnvc3: "",
      showCalendar: false,
      showCalendar2: false,
      // 保存的订单明细数据
      tempArr: [],
      // 订单表头
      orderTable: [],
      // 订单明细
      orderDetial: [],
      // 修改明细控制
      isShow: true,
      // 滚动target
      target: "",
      // 明细控制
      flag: false,
      // 返回图标控制
      isIconShow: false,
    };
  },
  created() {
    // 挂载部门和业务员
    this.getPersonData();
    // // 滚动target
    // this.target = document.getElementById("orderDetailForm");
    // document.getElementById("Bastic").scrollIntoView();
    // 获取当前日期
    this.getDate();
    // // 获取session中的订单信息
    this.getGoods();
    // 查看订单功能
    this.queryDetail();
  },
  mounted() {
    // 查询客户
    // this.findClient();
    // 返回按钮事件
    // // 如果支持 popstate 一般移动端都支持了
    // if (window.history && window.history.pushState) {
    //   // 往历史记录里面添加一条新的当前页面的url
    //   history.pushState(null, null, document.URL);
    //   // 给 popstate 绑定一个方法 监听页面刷新
    //   // window.addEventListener("popstate", this.backChange, false); //false阻止默认事件
    // }
  },
  beforeDestroy() {
    // 清空存货session
    this.$session.set("goodList", "");
    let goodList = this.$session.get("goodList");
    // window.removeEventListener("popstate", this.backChange, false); //false阻止默认事件
    let obj = {};
    // 路由跳转存储数据
    obj.formData = this.formData;
    // 文件
    obj.fileList = this.fileList;
    // 存货数据
    obj.tempArr = this.tempArr;
    // this.$session.set("orderData", JSON.stringify(obj));
    this.save_orderData(obj);
  },
  destroyed() {},
  beforeRouteLeave: (to, from, next) => {
    if (to.name === "stockPage") {
      next();
      //
    } else if (to.name === "loginPage") {
      next();
    } else {
      Dialog.confirm({
        title: "提示",
        message: "离开页面数据无法保存，确认离开？",
      })
        .then(() => {
          // on confirm
          // 路由跳转
          next();
        })
        .catch(() => {
          // on cancel
          next(false);
        });
    }
  },
  methods: {
    ...mapMutations(
      "orderData/",
      // 语法糖
      ["save_orderData"]
    ),
    // 是否包邮
    onSelectBaoyou() {},
    // 是否账期选择
    onSelectZhangqi() {},
    // 下拉刷新事件
    onLoad() {
      this.findClient();
    },
    onRefresh() {
      // 清空列表数据
      this.finished = false;
      this.cusColumns = [];
      this.page = 1;
      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      this.loading = true;
      this.onLoad();
    },
    // 获取session中的业务员信息
    getPersonData() {
      let person = this.$session.get("person");
      // 部门
      this.formData.iddepartment = JSON.parse(person).departmentId;
      this.iddepartment = JSON.parse(person).departmentName;
      // 业务员
      this.formData.idclerk = JSON.parse(person).personId;
      this.idclerk = JSON.parse(person).personName;
    },
    onOversize(file) {
      Toast("文件大小不能超过 5MB");
    },
    // 文件选择之后的回调
    afterRead(event) {
      // // 创建新的图片对象
      let img = new Image();
      // // 指定图片的DataURL(图片的base64编码数据)
      img.src = event.content;
      let obj = this.compress(img, 0.6);
      // 此时可以将压缩过的图片存入数组
      this.formData.fileList = this.fileList.map((ele) => {
        return {
          imgByte: obj,
        };
        // return { imgByte: delPic(ele.content) };
        // this.formData.imgByte.push(delPic(ele.content))
      });
    },
    // 压缩图片
    compress(img, size) {
      let canvas = document.createElement("canvas");
      let ctx = canvas.getContext("2d");
      let initSize = img.src.length;
      let width = img.width;
      let height = img.height;
      canvas.width = width;
      canvas.height = height;
      // 铺底色
      ctx.fillStyle = "#fff";
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      ctx.drawImage(img, 0, 0, width, height);
      //进行最小压缩
      let ndata = canvas.toDataURL("image/png", size);
      return ndata;
    },
    // 获取选择的存货
    getGoods() {
      let checkOrder = this.$route.query.checkOrder;
      // this.title = "查看订单";
      // this.isIconShow = true;
      if (checkOrder) {
        // let orderData = this.$session.get("orderData");
        let orderData = this.$store.state.orderData.orderData;
        this.formData = orderData.formData;
        this.fileList = orderData.fileList;
        // this.tempArr = JSON.parse(orderData).tempArr;
        let tempArr = this.$session.get("goodList");
        tempArr != ""
          ? (this.tempArr = JSON.parse(tempArr))
          : (this.tempArr = orderData.tempArr);
        if (tempArr != "") {
          this.tempArr = JSON.parse(tempArr);
          // 计算数量2
          this.tempArr.filter((ele) => {
            if (ele.gift === 1) {
              ele.price = 0;
            } else {
              ele.price <= ele.invSCost && (ele.price = ele.invSCost);
            }
            this.onCountNum(ele, true);
          });
        } else {
          this.tempArr = orderData.tempArr;
        }
      } else {
        // 查询编码
        this.findCode();
      }
    },
    // 跳转到选存货页面
    onSelectGoods() {
      if (this.formData.idcustomer != "") {
        // this.$session.set("isIconShow",true)
        // 新增，修改方法判断字段
        this.isIconShow === true
          ? this.$session.set("isIconShow", true)
          : this.$session.set("isIconShow", false);
        let obj = {};
        obj.formData = this.formData;
        obj.formData.id = this.id;
        // 文件
        obj.fileList = this.fileList;
        // 存货数据
        obj.tempArr = this.tempArr;
        // eventBus.$emit("orderData", obj);
        // this.$session.set("orderData", JSON.stringify(obj));
        this.save_orderData(obj);
        let orderData = this.$store.state.orderData.orderData;

        this.$router.push({
          name: "stockPage",
        });
      } else {
        Toast("请先选择客户！");
      }
    },
    // 补0函数
    Appendzero(obj) {
      if (obj < 10) return "0" + "" + obj;
      else return obj;
    },
    // 获取当前日期
    getDate() {
      //创建现在的时间
      var data = new Date();
      //获取年
      var year = data.getFullYear();
      //获取月
      var mon = data.getMonth() + 1;
      //获取日
      var day = data.getDate();
      this.formData.voucherdate = `${year}/${this.Appendzero(
        mon
      )}/${this.Appendzero(day)}`;
    },
    // 单价校验
    validator(item) {
      // .price,item.invSCost
      if (Number(item.invSCost) > Number(item.price)) {
        this.errorMessage = "请输入正确价格！";
        Toast("单价不得低于最低售价！");
        return false;
      } else {
        this.errorMessage = "";
        return true;
      }
    },
    //校验单价是否低于最低售价
    onJudgePrice(item) {
      let price = item.price;
      let invSCost = item.invSCost;
      this.total = 0;
      this.tempArr.filter((ele) => {
        if (item.id === ele.id) {
          ele.total = (Number(ele.quantity) * Number(ele.price)).toFixed(2);
        }
        this.total = (Number(this.total) + Number(ele.total)).toFixed(2);
      });
      if (Number(invSCost) > Number(price)) {
        Toast("单价不得低于最低售价！");
        this.submitLoading = false;
        return false;
      } else {
        return true;
      }
    },
    // 计算数量2
    onCountNum(item, flag) {
      let num = item.quantity;
      let quantity2 = (num / item.changeRate).toFixed(2);
      // nan非法检测
      isNaN(quantity2) === true && (quantity2 = 0);
      this.total = 0;
      this.tempArr.filter((ele) => {
        if (item.id === ele.id) {
          ele.quantity2 = quantity2;
          ele.total = (Number(ele.quantity) * Number(ele.price)).toFixed(2);
        }
        this.total = (Number(this.total) + Number(ele.total)).toFixed(2);
      });
    },
    // 返回
    onReturn() {
      this.$router.go(-1);
      // this.$router.push({ name: "searchPage" });
    },
    // 查看订单
    queryDetail() {
      // 获取路由上的id
      let id = this.$route.query.id;
      if (id != undefined) {
        this.$route.query.status === "驳回" ||
        this.$route.query.status === "审核中"
          ? (this.status = false)
          : (this.status = true);
        // this.status = this.$route.query.status;
        this.title = "查看订单";
        this.isIconShow = true;
        this.$session.set("isIconShow", true);
        // this.$session.set("isIconShow",true)
        let DsName = this.$session.get("DsName");
        let condition = {
          DsName: JSON.parse(DsName),
          id: id,
        };

        queryOrderDetial(condition, (data) => {
          // 订单表头
          this.orderTable = data.param;
          // 文件
          this.fileList = data.fileList;
          this.fileList.map((ele) => {
            ele.content = ele.imgByte;
          });
          // 订单明细
          this.tempArr = data.data;
          this.tempArr.filter((ele) => {
            ele.name = ele.inventoryName;
            ele.price = ele.origDiscountPrice;
            // 计算价格
            ele.total = (Number(ele.quantity) * Number(ele.price)).toFixed(2);
            this.total = (Number(this.total) + Number(ele.total)).toFixed(2);
          });
          this.formData = this.orderTable[0];
          // 单据编号
          this.code = this.orderTable[0].code;
          this.formData.reciveType = "其他";
          // 部门
          this.iddepartment = this.formData.departmentName;
          // 业务员
          this.idclerk = this.formData.personName;

          // 单据id
          this.id = this.orderTable[0].id;
          // // 调用index组件修改active的值
          // this.$emit("fatherMethod");
          // 查询客户带的收货地址
          let condition = {
            DsName: JSON.parse(DsName),
            idpartner: this.formData.idcustomer,
          };
          queryAddress(condition, (data) => {
            this.addColumns = data.data;
            // let addressObj = this.addColumns.filter((ele) => {
            //   return ele.isDefaultAddress === 1;
            // });
            // this.formData.address = addressObj[0].address;
            // this.formData.linkMan = addressObj[0].linkMan;
            // this.formData.contactPhone = addressObj[0].contactPhone;
          });
        });
        // 调用index组件修改active的值
        // return new Promise((res, rej) => {
        //   res();
        // }).then(() => {
        //   this.$emit("fatherMethod");
        // }).catch(()=>{});
      }
    },
    // 选客户
    showPopup() {
      if (this.status === false) {
        this.show = true;
        // 讲弹框打开的状态存入session，防止
        this.$session.set("showPopup", true);
        // 查询客户
        this.onRefresh();
      } else {
        this.show = false;
      }
    },
    // 选结算客户
    showPopup2() {
      if (this.status === false) {
        this.show2 = true;
        this.$session.set("showPopup", true);
        // 查询客户
        this.onRefresh();
      } else {
        this.show2 = false;
      }
    },

    // 选存货
    showPopup3() {
      this.show3 = true;
      this.findGoods();
    },
    // 查询编码
    findCode() {
      // 获取账套下的数据库
      let DsName = this.$session.get("DsName");
      let condition = {
        DsName: JSON.parse(DsName),
      };
      queryCode(condition, (data) => {
        this.formData.code = data.data.code;
      });
    },
    // 条件查询客户
    onFindClient() {
      this.page = 1;
      this.debounce(500);
    },
     //防抖debounce代码：
    debounce(wait) {
      let _this = this;
      if (this.timeout) clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        _this.onRefresh();
      }, wait);
    },
    // 查询客户
    findClient() {
      // let cusColumns = this.cusColumns;
      // let setCusColumns = this.setCusColumns;
      let DsName = this.$session.get("DsName");
      let condition = {
        DsName: JSON.parse(DsName),
        name: this.condition,
        page: this.page++,
        limit: this.limit,
        personId: this.formData.idclerk,
      };
      queryClient(condition, (data) => {
        let cusColumns = data.data;
        //  let setCusColumns = data.data;
        this.count = data.count;
        cusColumns.forEach((ele) => {
          this.cusColumns.push(ele);
        });
        // 加载状态结束
        this.loading = false;
        this.refreshing = false;
        // 数据全部加载完成
        if (this.cusColumns.length >= this.count) {
          this.finished = true;
        }
        // setCusColumns.forEach((ele) => {
        //   this.setCusColumns.push(ele);
        // });
        // // 数据全部加载完成
        // if (this.setCusColumns.length >= this.count) {
        //   this.finished = true;
        // }
      });
    },
    // 查询业务员
    findPerson(id) {
      let DsName = this.$session.get("DsName");

      let conditon = {
        id: id,
        DsName: JSON.parse(DsName),
      };
      queryPerson(conditon, (data) => {
        this.perColumns = data.data;
      });
    },
    // 查询部门
    findOrgs() {
      let DsName = this.$session.get("DsName");
      queryOrgs(JSON.parse(DsName), (data) => {
        this.orgColumns = data.data;
      });
    },
    // 查询存货
    findGoods() {
      // let _this=this;
      let DsName = this.$session.get("DsName");
      let condition = {
        DsName: JSON.parse(DsName),
        name: this.condition3,
      };
      queryGoods(condition, (data) => {
        this.goodColumns = data.data;
      });
    },
    // 查看明细
    onUpdateDetial(item, index) {
      this.activeNames = ["0", "1"];
      // 挂载明细表单数据
      this.formData2 = item;
      this.idunit = item.idunit;
      this.idunit2 = item.idunit2;
      this.idinventory = item.name;
      this.unitExchangeRate = item.unitExchangeRate;
      this.idinventory2 = index;
      // 平滑滚动至添加明细的表单
      let target = document.getElementById("orderDetailForm");
      target.scrollIntoView({
        behavior: "smooth",
        block: "start",
        inline: "nearest",
      });
      this.flag = true;
    },
    // 删除明细
    onDelTeamArr(index) {
      this.tempArr.splice(index, 1);
      Toast("删除成功!");
    },

    // 日期选择
    onConfirm(date) {
      this.formData.voucherdate = `${date.getFullYear()}/${
        date.getMonth() + 1
      }/${date.getDate()}`;
      this.showCalendar = false;
    },
    // 账期到期时间选择
    onConfirm2(date) {
      this.formData.pubuserdefnvc3 = `${date.getFullYear()}/${this.Appendzero(
        date.getMonth() + 1
      )}/${this.Appendzero(date.getDate())}`;
      this.showCalendar2 = false;
    },
    // 业务类型选择
    onConfirmType(v) {
      this.formData.busitypeName = v.busitypeName;
      this.typeShowPicker = false;
    },
    // 选存货带出单位
    findUnits(idunitgroup) {
      let DsName = this.$session.get("DsName");
      let condition = {
        DsName: JSON.parse(DsName),
        idunitgroup: idunitgroup,
      };
      queryUnits(condition, (data) => {
        this.idunit2 = data.unit2;
        this.formData2.unitName2 = data.unitName2;
        this.unitExchangeRate = data.changeRate;
        // 计算数量2
        this.onCountNum();
      });
    },
    // 地址选择
    onConfirmAddress(v) {
      this.formData.address = v.address;
      this.formData.linkMan = v.linkMan;
      this.formData.contactPhone = v.contactPhone;
      this.addressShowPicker = false;
    },
    // 部门选择
    onConfirmOrg(v) {
      this.formData.iddepartment = v.id;
      this.iddepartment = v.name;
      //   this.className = v.text;
      this.orgShowPicker = false;
      // 查询业务员
      this.findPerson(v.id);
    },
    // 客户选择
    onConfirmCus(v) {
      this.formData.idcustomer = v.id;
      this.formData.partnerName = v.name;
      // 带出结算客户
      this.formData.idsettlecustomer = v.idsettlementPartner;
      this.formData.settlecustomerName = v.settlementName;
      //   this.className = v.text;
      this.show = false;
      // 清空
      this.cusColumns = [];
      // 选客户带出地址等信息
      let DsName = this.$session.get("DsName");
      let condition = {
        DsName: JSON.parse(DsName),
        idpartner: this.formData.idcustomer,
      };

      queryAddress(condition, (data) => {
        this.addColumns = data.data;
        let addressObj = this.addColumns.filter((ele) => {
          return ele.isDefaultAddress === 1;
        });
        this.formData.address = addressObj[0].address;
        this.formData.linkMan = addressObj[0].linkMan;
        this.formData.contactPhone = addressObj[0].contactPhone;
      });
      Toast("选择客户成功!");
      // this.cusShowPicker = false;
    },
    // 结算客户选择
    onConfirmSetCus(v) {
      this.formData.idsettlecustomer = v.id;
      this.formData.settlecustomerName = v.name;
      // 清空
      this.cusColumns = [];
      //   this.className = v.text;
      this.show2 = false;
      Toast("选择结算客户成功");
      // this.setCusShowPicker = false;
    },
    onCancelDig() {
      this.show = false;

      this.show2 = false;
    },
    // 业务员选择
    onConfirmPer(v) {
      this.formData.idclerk = v.id;
      this.idclerk = v.name;
      //   this.className = v.text;
      this.perShowPicker = false;
    },
    // 保存
    onSubmit(value) {
      // 按钮加载状态
      this.submitLoading = true;
      this.formData.fileList = this.fileList.map((ele) => {
        return {
          imgByte: delPic(ele.content),
        };
        // this.formData.imgByte.push(delPic(ele.content))
      });
      let obj = this.formData;

      // 表头
      let user = this.$session.get("user");
      let DsName = this.$session.get("DsName");
      obj.maker = JSON.parse(user).name;
      obj.DsName = JSON.parse(DsName);
      // every 返回false时中断遍历,返回true继续遍历
      let flag = this.tempArr.every((ele) => {
        if (ele.gift != 1) {
          return this.onJudgePrice(ele);
        } else {
          return true;
        }
      });
      if (flag) {
        let isIconShow = this.$session.get("isIconShow");
        if (isIconShow) {
          // 修改
          obj.children = this.tempArr;
          // obj.id = this.id;
          obj.code = this.code;
          updateOrder(obj, (data) => {
            data.success === true ? Toast(data.info) : Toast(data.info);
            this.submitLoading = false;
          });
        } else {
          // 新增
          // 表体 idinventory
          // 将赠品的价格修改为0
          this.tempArr.map((ele) => {
            ele.idinventory = ele.id;
            ele.gift === 1 && (ele.price = 0);
            return ele;
          });
          obj.children = this.tempArr;
          submitOrder(obj, (data) => {
            data.success === true
              ? (Toast(data.info),
                // 清空数据和session
                this.$session.set("goodList", ""),
                this.save_orderData(""),
                // this.$session.set("orderData", ""),
                (this.formData.pubuserdefnvc1 = "否"),
                (this.formData.pubuserdefnvc3 = ""),
                (this.formData.pubuserdefdecm2 = 0),
                (this.formData.pubuserdefnvc8 = "包邮"),
                (this.formData.idcustomer = ""),
                (this.formData.linkMan = ""),
                (this.formData.contactPhone = ""),
                (this.formData.waybillNumber = ""),
                (this.formData.partnerName = ""),
                (this.formData.idsettlecustomer = ""),
                (this.formData.settlecustomerName = ""),
                (this.formData.address = ""),
                (this.formData.memo = ""),
                (this.formData.pubuserdefnvc4 = ""),
                (this.fileList = []),
                this.findCode(),
                (this.tempArr = []))
              : Toast(data.info);
            this.submitLoading = false;
          });
        }
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.order-content {
  .login-header {
    height: 60px;
    width: 100%;
    color: white;
    line-height: 60px;
    background-color: #1989fa;
    position: fixed;
    top: 0px;
    left: 0px;
    z-index: 1;

    .icon-content {
      text-align: left;
      margin-left: 20px;
    }

    // position: absolute;
    // top: 0px;
  }

  .orderTable-content {
    margin-top: 60px;
  }

  .custom-title {
    float: left;
  }

  .van-cell__value {
    text-align: center;
  }

  .popup-class {
    .search-content {
      margin-top: 0px;
    }
  }

  .detail-box {
    margin: 5px 15px;

    .detail-title {
      // font-weight: bold;
      text-align: left;
    }

    .detail-content {
      // margin-bottom: 5px;
      font-size: 12px;
      text-align: left;
      color: #ccc;
    }
  }

  .van-button--square {
    border-radius: 0;
    height: 100% !important;
  }
}
</style>
